import MIMCSocket from './mimc'
import EventEmitter from './events' 

var wsUrl = "";
//环境设置
if (process.env.NODE_ENV == 'dev') {
  wsUrl = 'ws://192.168.0.43:30099';
} else if (process.env.NODE_ENV == 'test') {
  wsUrl = 'ws://192.168.0.43:30099';
} else if (process.env.NODE_ENV == 'uat') {
  wsUrl = 'ws://192.168.0.43:30099';
} else if (process.env.NODE_ENV == 'release') {
  wsUrl = 'ws://192.168.0.43:30099';
}

export default (function () {
  var instantiated;
  class MIMC {
    constructor() {
      var socket;
      var events = new EventEmitter();
      function createSocket() {
        if (socket != undefined)
        {
          console.error("当前链接已经存在");
          return;
        }
        socket = new MIMCSocket(wsUrl);
        socket.registerMsgHandler((message) => {
          onWSMessage(message);
        });
        socket.registerDisconnectHandler((error) => {
          onWSDisconnect(error);
        });
      }
      this.onWSLogon = function (params = {}) {
        createSocket();
        events.on('onWSLogon', function (msg) {
          console.log(params,msg);
        })
        socket.login();
      };

      this.sendWSMessage = function (url, params = {}) {
        // this.socket.sendWSMessage(params);
        console.log(url, params);
      };

      function onWSMessage(evt) {
        console.log(evt);
      }

      function onWSDisconnect(evt) {
        console.log(evt);
        //登录失败
        if (!socket.isLogin())
        { 
          events.emit('onWSLogon',false)
        }
      }
      
      //事件订阅
      this.addWSMessageListener = function (key,callfun) {
        events.on(key, function (msg) {
          if(typeof(callfun) == 'function')
          {
            callfun(msg);
          }
        })
      };

      //事件移除
      this.removeWSMessageListener = function (key) {
        events.off(key, function (msg) {
          console.log(msg)
        })
      };

    }
  }
  return {
    getInstance: () => {
      if (!instantiated)
      {
        instantiated = new MIMC();
      }
      return instantiated;
    },
  }
})();


